    {% extends "base.html" %}

    {% block content %}
    <div class="flex flex-col lg:flex-row gap-8">
        <!-- 问题描述区域 -->
        <div class="lg:w-2/3">
            <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h1 class="text-2xl font-bold text-dark mb-2">{{ problem.title }}</h1>
                        <div class="flex items-center gap-3">
                            {% if problem.difficulty == "简单" %}
                            <span class="px-3 py-1 rounded-full bg-success/10 text-success text-sm">简单</span>
                            {% elif problem.difficulty == "中等" %}
                            <span class="px-3 py-1 rounded-full bg-warning/10 text-warning text-sm">中等</span>
                            {% else %}
                            <span class="px-3 py-1 rounded-full bg-danger/10 text-danger text-sm">困难</span>
                            {% endif %}
                            
                            <span class="px-3 py-1 rounded-full bg-light-1 text-dark-2 text-sm flex items-center">
                                <i class="fa fa-users mr-1"></i> {{ problem.submissions|length }} 提交
                            </span>
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <!-- 收藏按钮 -->
                        <button id="favorite-btn" class="btn-secondary transition-all duration-200" 
                                data-problem-id="{{ problem.id }}"
                                data-is-favorited="{{ 'true' if is_favorited else 'false' }}">
                            <i class="fa fa-bookmark-o mr-1"></i> 
                            <span id="favorite-text">收藏</span>
                        </button>
                        <!-- 分享按钮 -->
                        <button class="btn-secondary" id="share-btn">
                            <i class="fa fa-share-alt mr-1"></i> 分享
                        </button>
                        <!-- 下一题按钮 -->
                        <button class="btn-secondary" id="next-problem-btn">
                            <i class="fa fa-chevron-right mr-1"></i> 下一题
                        </button>
                    </div>
                </div>
                
                <div class="prose max-w-none">
                    <h3 class="text-lg font-semibold text-dark mb-2">题目描述</h3>
                    <p class="text-dark-2 mb-4">{{ problem.description|replace('\n', '<br>')|safe }}</p>
                    
                    <h3 class="text-lg font-semibold text-dark mb-2">示例</h3>
                    {% if sample_case %}
                    <div class="bg-light-1 rounded-lg p-4 mb-4">
                        <p class="font-medium mb-2">输入:</p>
                        <pre class="bg-dark text-white p-3 rounded-lg overflow-x-auto">{{ sample_case.input_data }}</pre>
                        
                        <p class="font-medium mb-2 mt-4">输出:</p>
                        <pre class="bg-dark text-white p-3 rounded-lg overflow-x-auto">{{ sample_case.expected_output }}</pre>
                    </div>
                    {% else %}
                    <div class="bg-light-1 rounded-lg p-4 mb-4">
                        <p class="text-dark-2">暂无示例测试用例</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <!-- 代码编辑器和提交区域 -->
        <div class="lg:w-1/3">
            <div class="bg-white rounded-xl shadow-sm p-6 sticky top-24">
                <h2 class="text-xl font-semibold text-dark mb-4">提交代码</h2>
                
                <!-- 引入CodeMirror代码编辑器 -->
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/dracula.min.css">
                <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/clike/clike.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/java/java.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/addon/edit/closebrackets.min.js"></script>
                
                <form id="submit-form" action="{{ url_for('submit', problem_id=problem.id) }}" method="POST">
                    <!-- CSRF令牌 -->
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
     
                    <div class="mb-4">
                        <label for="language" class="block text-dark-2 mb-2">选择语言</label>
                        <select id="language" name="language" class="form-input">
                            <option value="cpp">C++</option>
                            <option value="python">Python 3</option>
                            <option value="java">Java</option>
                        </select>
                    </div>
                    
                    <div class="mb-4">
                        <label for="code" class="block text-dark-2 mb-2">代码</label>
                        <textarea id="code" name="code" rows="15" class="form-input font-mono" placeholder="在此输入你的代码..."></textarea>
                    </div>
                    
                    <button type="submit" id="submit-btn" class="btn-primary w-full flex items-center justify-center">
                        <i class="fa fa-paper-plane mr-2"></i> 提交代码
                    </button>
                </form>
                
                <!-- 提交结果展示区域 -->
                <div id="result-container" class="mt-6 hidden">
                    <h3 class="text-lg font-semibold text-dark mb-3">提交结果</h3>
                    
                    <div id="loading-indicator" class="flex items-center justify-center py-8">
                        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
                    </div>
                    
                    <div id="result-content" class="hidden">
                        <div id="success-result" class="hidden">
                            <div class="bg-success/10 rounded-lg p-4 mb-4">
                                <div class="flex items-center">
                                    <i class="fa fa-check-circle text-success text-2xl mr-2"></i>
                                    <h4 class="font-semibold text-success">答案正确</h4>
                                </div>
                                <p class="mt-2">执行时间: <span id="execution-time"></span> 秒</p>
                            </div>
                        </div>
                        
                        <div id="error-result" class="hidden">
                            <div class="bg-danger/10 rounded-lg p-4 mb-4">
                                <div class="flex items-center">
                                    <i class="fa fa-times-circle text-danger text-2xl mr-2"></i>
                                    <h4 class="font-semibold text-danger" id="error-type">答案错误</h4>
                                </div>
                                <p class="mt-2" id="error-message"></p>
                            </div>
                            
                            <div class="bg-light-1 rounded-lg p-4">
                                <h5 class="font-medium mb-2">测试用例结果</h5>
                                <div id="test-case-results" class="space-y-2 max-h-60 overflow-y-auto"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 居中Toast提示组件 -->
    <div id="toast-container" class="fixed inset-0 flex items-center justify-center z-50 pointer-events-none">
        <div id="toast" class="bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg opacity-0 scale-0 transition-all duration-300 flex items-center">
            <span id="toast-message"></span>
            <button id="toast-close" class="ml-4 text-white hover:text-gray-300" onclick="closeToast()">
                <i class="fa fa-times"></i>
            </button>
        </div>
    </div>

    <script>
        // 从后端接收的初始数据
        const initialCodes = {{ initial_codes|tojson }};
        const functionSignatures = {{ function_signatures|tojson }};
        const currentProblemId = {{ problem.id }};
        const totalProblems = {{ total_problems|default(0) }};

        // 初始化代码编辑器
        const editor = CodeMirror.fromTextArea(document.getElementById('code'), {
            lineNumbers: true,
            theme: "dracula",
            autoCloseBrackets: true,
            mode: "text/x-python"  // 默认Python模式
        });

        // 语言选择变化事件
        document.getElementById('language').addEventListener('change', function() {
            const lang = this.value;
            
            // 切换编辑器模式
            if (lang === 'python') {
                editor.setOption('mode', 'text/x-python');
            } else if (lang === 'java') {
                editor.setOption('mode', 'text/x-java');
            } else if (lang === 'cpp') {
                editor.setOption('mode', 'text/x-c++src');
            }
            
            // 加载对应语言的函数签名和初始代码
            const signature = functionSignatures[lang] || '';
            const code = initialCodes[lang] || '';
            
            // 合并函数签名和代码（按语言格式处理）
            let combinedCode = '';
            if (lang === 'python') {
                combinedCode = `${signature}\n${indentCode(code, 4)}`;
            } else if (lang === 'java') {
                combinedCode = `${signature} {\n${indentCode(code, 4)}\n}`;
            } else if (lang === 'cpp') {
                combinedCode = `${signature} {\n${indentCode(code, 4)}\n}`;
            } else {
                combinedCode = `${signature}\n${code}`;
            }
            
            editor.setValue(combinedCode);
            // 定位光标到函数体开始位置
            if (lang === 'python') {
                editor.setCursor(1, 4);
            } else if (lang === 'java' || lang === 'cpp') {
                editor.setCursor(1, 4);
            }
        });

        // 代码缩进辅助函数
        function indentCode(code, spaces) {
            if (!code.trim()) return '';
            const indent = ' '.repeat(spaces);
            return code.split('\n').map(line => indent + line).join('\n');
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 触发语言选择事件，初始化编辑器
            document.getElementById('language').dispatchEvent(new Event('change'));
            
            // 初始化收藏按钮状态
            const favoriteBtn = document.getElementById('favorite-btn');
            updateFavoriteButton(favoriteBtn);
            
            // 绑定收藏按钮点击事件
            favoriteBtn.addEventListener('click', toggleFavorite);

            // 绑定分享按钮点击事件
            const shareBtn = document.getElementById('share-btn');
            shareBtn.addEventListener('click', async function() {
                try {
                    const currentUrl = window.location.href;
                    await navigator.clipboard.writeText(currentUrl);
                    showCenterToast('链接已复制到剪贴板', 'success');
                    
                    // 临时修改按钮状态
                    const originalHTML = shareBtn.innerHTML;
                    shareBtn.innerHTML = '<i class="fa fa-check mr-1"></i> 已复制';
                    setTimeout(() => {
                        shareBtn.innerHTML = originalHTML;
                    }, 2000);
                    
                } catch (error) {
                    console.error('复制链接失败:', error);
                    showCenterToast('复制失败，请手动复制链接', 'error');
                }
            });

            // 找到“下一题”点击事件代码，添加调试
            const nextProblemBtn = document.getElementById('next-problem-btn');
            nextProblemBtn.addEventListener('click', function() {
                const nextId = getNextProblemId(currentProblemId);
                console.log('计算的下一题ID:', nextId); // 调试：打印ID
                if (nextId) {
                    window.location.href = `/problem/${nextId}`;
                } else {
                    showCenterToast('已是最后一题', 'info');
                }
            });
        });

        let validProblemIds = [];

        // 页面加载时，获取有效题目 ID 列表
        document.addEventListener('DOMContentLoaded', async function() {
            try {
                // 调用后端接口，获取有效 ID 列表
                const response = await fetch('/api/problems/valid_ids');
                const data = await response.json();
                validProblemIds = data.valid_ids;
            } catch (error) {
                console.error('获取有效题目 ID 失败:', error);
                validProblemIds = []; // 降级为空列表
            }
        });

        // 计算下一题 ID（基于真实有效 ID 列表）
        function getNextProblemId(currentId) {
            // 查找当前 ID 在有效列表中的位置
            const currentIndex = validProblemIds.indexOf(currentId);
            
            // 判断是否有下一题
            if (currentIndex !== -1 && currentIndex < validProblemIds.length - 1) {
                return validProblemIds[currentIndex + 1]; // 返回下一个有效 ID
            }
            return null; // 无下一题
        }

        // 更新收藏按钮样式
        function updateFavoriteButton(button) {
            const isFavorited = button.dataset.isFavorited === 'true';
            const icon = button.querySelector('i');
            const text = button.querySelector('span');
            
            button.classList.remove(
                'bg-white', 'text-dark', 'border-light-2', 'hover:bg-gray-50',
                'bg-yellow-50', 'text-yellow-600', 'hover:bg-yellow-100'
            );
            
            if (isFavorited) {
                icon.classList.remove('fa-bookmark-o');
                icon.classList.add('fa-bookmark', 'text-yellow-500');
                text.textContent = '已收藏';
                button.classList.add('bg-yellow-50', 'text-yellow-600', 'hover:bg-yellow-100');
            } else {
                icon.classList.remove('fa-bookmark', 'text-yellow-500');
                icon.classList.add('fa-bookmark-o');
                text.textContent = '收藏';
                button.classList.add('bg-white', 'text-dark', 'border-light-2', 'hover:bg-gray-50');
            }
        }

        // 切换收藏状态
        async function toggleFavorite() {
            const favoriteBtn = document.getElementById('favorite-btn');
            const problemId = favoriteBtn.dataset.problemId;
            const isFavorited = favoriteBtn.dataset.isFavorited === 'true';
            
            // 临时更新UI
            favoriteBtn.dataset.isFavorited = (!isFavorited).toString();
            updateFavoriteButton(favoriteBtn);
            favoriteBtn.disabled = true;
            
            try {
                // 发送请求到后端
                const response = await fetch(`/toggle_favorite/${problemId}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content,
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) throw new Error(`服务器错误: ${response.status}`);
                const data = await response.json();
                
                if (data.status === 'success') {
                    favoriteBtn.dataset.isFavorited = data.is_favorited.toString();
                    updateFavoriteButton(favoriteBtn);
                    showCenterToast(data.message || (data.is_favorited ? '收藏成功' : '取消收藏成功'));
                } else {
                    throw new Error(data.message || '操作失败');
                }
            } catch (error) {
                console.error('收藏失败:', error);
                // 回滚状态
                favoriteBtn.dataset.isFavorited = isFavorited.toString();
                updateFavoriteButton(favoriteBtn);
                showCenterToast(error.message || '网络错误，请重试', 'error');
            } finally {
                favoriteBtn.disabled = false;
            }
        }

        // 显示提示框
        function showCenterToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const messageSpan = document.getElementById('toast-message');
            
            messageSpan.textContent = message;
            toast.className = `bg-${type === 'success' ? 'green' : type === 'error' ? 'red' : 'blue'}-500 text-white px-6 py-3 rounded-lg shadow-lg 
                            opacity-0 scale-0 transition-all duration-300 flex items-center pointer-events-auto`;
            
            // 显示动画
            setTimeout(() => {
                toast.classList.remove('opacity-0', 'scale-0');
                toast.classList.add('opacity-100', 'scale-100');
            }, 10);
            
            // 自动关闭
            setTimeout(closeToast, 3000);
        }

        // 关闭提示框
        function closeToast() {
            const toast = document.getElementById('toast');
            toast.classList.remove('opacity-100', 'scale-100');
            toast.classList.add('opacity-0', 'scale-0');
        }

        // 代码提交处理
        document.getElementById('submit-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 显示加载状态
            document.getElementById('result-container').classList.remove('hidden');
            document.getElementById('loading-indicator').classList.remove('hidden');
            document.getElementById('result-content').classList.add('hidden');
            document.getElementById('success-result').classList.add('hidden');
            document.getElementById('error-result').classList.add('hidden');
            
            // 收集表单数据
            const formData = new FormData(this);
            
            // 发送提交请求
            fetch(this.action, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('loading-indicator').classList.add('hidden');
                document.getElementById('result-content').classList.remove('hidden');
                
                if (data.status === 'accepted') {
                    // 提交成功
                    document.getElementById('success-result').classList.remove('hidden');
                    document.getElementById('execution-time').textContent = data.execution_time.toFixed(3);
                } else {
                    // 提交失败
                    document.getElementById('error-result').classList.remove('hidden');
                    const errorTypeEl = document.getElementById('error-type');
                    const errorMsgEl = document.getElementById('error-message');
                    
                    // 根据错误类型显示信息
                    if (data.status === 'wrong_answer') {
                        errorTypeEl.textContent = '答案错误';
                        errorMsgEl.textContent = '你的代码没有通过所有测试用例';
                    } else if (data.status === 'time_limit_exceeded') {
                        errorTypeEl.textContent = '超时';
                        errorMsgEl.textContent = '你的代码执行时间超过了限制';
                    } else if (data.status === 'runtime_error') {
                        errorTypeEl.textContent = '运行时错误';
                        if (data.results[0]?.error?.includes('Segmentation fault')) {
                            errorMsgEl.textContent = '段错误（可能是数组越界、空指针引用等问题）';
                        } else if (data.results[0]?.error?.includes('Floating point exception')) {
                            errorMsgEl.textContent = '浮点异常（可能是除以零等问题）';
                        } else {
                            errorMsgEl.textContent = data.results[0]?.error || '未知运行时错误';
                        }
                    } else if (data.status === 'compilation_error') {
                        errorTypeEl.textContent = '编译错误';
                        let errorMsg = data.results[0]?.error || '未知编译错误';
                        if (errorMsg.includes('error:')) {
                            const firstError = errorMsg.split('\n').find(line => line.includes('error:'));
                            if (firstError) {
                                errorMsg = firstError;
                                const match = firstError.match(/solution\.cpp:(\d+):(\d+): error: (.*)/);
                                if (match) {
                                    errorMsg = `第 ${match[1]} 行，第 ${match[2]} 列：${match[3]}`;
                                }
                            }
                        }
                        errorMsgEl.textContent = errorMsg;
                    } else {
                        errorTypeEl.textContent = '其他错误';
                        errorMsgEl.textContent = data.status;
                    }
                    
                    // 显示测试用例结果
                    const resultsContainer = document.getElementById('test-case-results');
                    resultsContainer.innerHTML = '';
                    data.results.forEach((testCase, index) => {
                        const el = document.createElement('div');
                        el.className = 'p-3 rounded-lg';
                        
                        if (testCase.status === 'accepted') {
                            el.classList.add('bg-success/10', 'text-success');
                            el.innerHTML = `
                                <div class="flex items-center">
                                    <i class="fa fa-check-circle mr-2"></i>
                                    <span>测试用例 ${index + 1}: 通过</span>
                                </div>
                                <p class="text-sm mt-1 ml-6">执行时间: ${testCase.execution_time.toFixed(3)} 秒</p>
                            `;
                        } else {
                            el.classList.add('bg-danger/10', 'text-danger');
                            el.innerHTML = `
                                <div class="flex items-center">
                                    <i class="fa fa-times-circle mr-2"></i>
                                    <span>测试用例 ${index + 1}: 失败</span>
                                </div>
                                <div class="text-sm mt-2 ml-6 space-y-2">
                                    <p><span class="font-medium">输入:</span> ${testCase.input}</p>
                                    <p><span class="font-medium">预期输出:</span> ${testCase.expected_output}</p>
                                    <p><span class="font-medium">实际输出:</span> ${testCase.actual_output}</p>
                                    ${testCase.error ? `<p><span class="font-medium">错误:</span> ${testCase.error}</p>` : ''}
                                </div>
                            `;
                        }
                        resultsContainer.appendChild(el);
                    });
                }
            })
            .catch(error => {
                // 网络错误
                document.getElementById('loading-indicator').classList.add('hidden');
                document.getElementById('result-content').classList.remove('hidden');
                document.getElementById('error-result').classList.remove('hidden');
                document.getElementById('error-type').textContent = '提交失败';
                document.getElementById('error-message').textContent = '无法连接到服务器，请稍后再试';
            });
        });
    </script>
    {% endblock %}